<template>
  <el-dialog
    title="指派负责人"
    :visible.sync="visible"
    width="850px"
    append-to-body
  >
    <avue-form
      ref="addForm"
      v-model="form"
      :option="directorFormOption"
    >
      <template #userIds="{ disabled }">
        <el-select
          v-model="form.userIds"
          clearable
          :disabled="disabled"
          multiple
          placeholder="请选择负责人，支持多选"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name + '(' + item.phone + ')'"
            :value="item.userId"
          ></el-option>
        </el-select>
      </template>
    </avue-form>
    <template #footer>
      <el-button
        type="primary"
        :loading="loading"
        @click="assignAdoptPerson"
      >
        确定
      </el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { directorFormOption } from '@/const/crud/pet/adoptionRecord';
import { assignAdoptPerson } from '@/api/core/adopt';
import { fetchAdminList } from '@/api/admin/client';
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    info: {
      type: Object,
    },
  },
  data() {
    return {
      directorFormOption,
      form: {},
      loading: false,
      userList: [],
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.form = this.info;
        this.form.userIds = [];
        this.fetchAdminList();
      } else {
        this.$refs.addForm && this.$refs.addForm.resetFields();
      }
    },
  },
  methods: {
    assignAdoptPerson() {
      this.$refs.addForm.validate(async (valid, done) => {
        if (valid) {
          const userIds = [];
          this.form.userIds.forEach((element) => {
            if (element) {
              userIds.push(element);
            }
          });
          const data = {
            id: this.info.id,
            userIds,
          };
          try {
            this.loading = true;
            await assignAdoptPerson(data);
            this.visible = false;
            this.$emit('onSuccess');
            this.loading = false;
            done();
          } catch (error) {
            this.loading = false;
            done();
            throw new Error(error);
          }
        }
      });
    },
    fetchAdminList() {
      fetchAdminList().then((res) => {
        this.userList = res.data.data;
      });
    },
  },
};
</script>
